package com.xuecheng.order.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.xuecheng.api.order.OrderApi;
import com.xuecheng.api.order.model.dto.OrdersDTO;
import com.xuecheng.api.order.model.vo.QueryOrderModel;
import com.xuecheng.common.domain.page.PageRequestParams;
import com.xuecheng.common.domain.page.PageVO;
import com.xuecheng.order.common.utils.UAASecurityUtil;
import com.xuecheng.order.service.OrdersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * <p>
 * 订单 前端控制器
 * </p>
 *
 * @author itcast
 */
@Slf4j
@RestController
@RequestMapping
public class OrdersController implements OrderApi {

    @Autowired
    private OrdersService ordersService;

    @GetMapping("orders/create/{coursePubId}")
    public OrdersDTO createOrModifyOrder(@PathVariable Long coursePubId) {
        //获得用户名
        String username = UAASecurityUtil.getUser().getUsername();

        return ordersService.createOrModifyOrder(coursePubId, username);
    }

    /*  当前的方法会被第三方平台来调用，此方法的接口方法不需要在xc-api工程中进行定义
     *       xc-api 工程的方法
     *           1.学成的前端调用的方法
     *           2.学成微服务远程调用方法
     * */
    @RequestMapping("order-pay/wx-pay/notify-result")
    public String notifyPayResult(HttpServletRequest request, HttpServletResponse response) {

        String xmlResult = null;
        try {
            xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
        } catch (IOException e) {
            return WxPayNotifyResponse.fail("获得支付结果数据失败");
        }

        return ordersService.notifyPayResult(xmlResult);
    }

    @GetMapping("order/{orderNo}")
    public Map<String, Object> refreshPayResult(@PathVariable String orderNo) {

        return ordersService.refreshPayResult(orderNo);
    }

    @PostMapping("orders/my-list")
    public PageVO<OrdersDTO> queryOrderList(PageRequestParams params, @RequestBody QueryOrderModel model) {

        //获得用户名
        String username = UAASecurityUtil.getUser().getUsername();

        return ordersService.queryOrderList(params, model, username);
    }
}
